import requests
import json
from flask import Flask, request, jsonify
from flask_cors import CORS
import time
import pymysql
from pymysql.cursors import DictCursor
import traceback  # 用于获取详细的错误堆栈信息
app = Flask(__name__)
CORS(app)  # 启用 CORS，允许跨域请求

# 数据库配置 - 根据实际情况修改
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '4014',
    'database': 'lqb',
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}

API_KEY = "6jPaXeWH2HbfXsfaJo76vAub"
SECRET_KEY = "31cO2arqq9zGtlGXOQ78OFSW4qpK19b3"
@app.route('/image', methods=['POST'])
def image_message():
    try:
        # 获取前端发送的 JSON 数据
        data = request.get_json()
        real_data = json.loads(data['data'])
        # print(real_data)  # 打印原始数据，便于调试
        image1 = real_data['image1']
        image2 = real_data['image2']
        result= faceRecognize(image1,image2)
        print(image1)
        # print(result)
        return result
    except Exception as e:
        # 错误处理
        return jsonify({'error': str(e)}), 500
@app.route('/imagebase', methods=['POST'])
def name_message():
    try:
        # 获取前端发送的 JSON 数据
        data = request.get_json()
        # print(f"接收到的原始数据: {data}")  # 打印原始数据，便于调试

        # 验证数据格式
        if not isinstance(data, dict):
            raise ValueError("数据格式应为 JSON 对象")
        if 'Name' not in data:
            raise ValueError("数据必须包含 Name 字段")

        # 拉取数据库数据
        name = data['Name']
        print(f"查询数据库中 Name 为 '{name}' 的图像")
        image_data = get_image_from_database(name)

        if image_data is None:
            return jsonify({'error': f"未找到姓名为 '{name}' 的图像"}), 404

        print(f"成功获取图像数据，长度: {len(image_data)} 字节")

        # 返回数据库中查询到的图像，而不是前端传来的图像
        return jsonify({"Name": name, "Image": image_data})

    except Exception as e:
        # 记录详细的错误信息
        error_info = traceback.format_exc()
        print(f"处理请求时发生错误: {str(e)}")
        print(f"错误堆栈:\n{error_info}")

        # 返回友好的错误信息给前端
        return jsonify({'error': f"服务器内部错误: {str(e)}"}), 500

def faceRecognize(image1,image2):
    url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + get_access_token()

    payload = json.dumps([
        {
            "image":image1,
            "image_type": "BASE64"
        },
        {
            "image":image2,
            "image_type": "BASE64"
        }
    ], ensure_ascii=False)
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    # print(response.text)
    return response.text

def get_image_from_database(name):
    """从数据库查询人脸图像数据"""
    try:
        print(f"尝试连接数据库: {DB_CONFIG['host']}/{DB_CONFIG['database']}")
        with pymysql.connect(**DB_CONFIG) as connection:
            print("数据库连接成功")
            with connection.cursor() as cursor:
                sql = "SELECT Image FROM Face WHERE Name = %s"
                cursor.execute(sql, (name,))
                result = cursor.fetchone()

                if result:
                    print("查询成功，已获取图像数据")
                    return result['Image']

                print(f"未找到姓名为 '{name}' 的记录")
                return None

    except pymysql.Error as e:
        # 专门处理数据库错误
        print(f"数据库操作失败: {e}")
        # 可以在这里添加数据库连接重试逻辑
        raise

    except Exception as e:
        print(f"查询失败: {e}")
        raise
def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    app.run(debug=True, port=5003)